package com.bs.jianli.util.auto;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bs.jianli.entity.User;
import com.bs.jianli.util.exception.NoAuthException;
import com.bs.jianli.util.exception.NotUserException;
import com.bs.jianli.util.redis.RedisUtils;
import com.bs.jianli.util.redis.TokenUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author 小姚
 * @pakeageName:com.bs.jianli.util.auto
 * @ClassName:AopAuth
 * @Descirption:
 * @data 2023/1/13 19:14
 */
//@Component
//@Aspect
public class AopAuth {

    @Resource
    HttpServletRequest request;

    @Resource
    RedisUtils utils;

    @Around("execution(* com.bs.jianli.controller.*.*(..)) && @annotation(Auth)")
    public Object getBefore(ProceedingJoinPoint point) throws Throwable {
        String token = request.getHeader(TokenUtil.TOKEN_NAME);
        if(StringUtils.isBlank(token)){
            throw new NotUserException("您还未登录");
        }
        Object o=null;
        User user =(User) utils.get(token);
        if(user==null){
            throw new NotUserException("您还未登录");
        }
        Signature signature = point.getSignature();
        MethodSignature methodSignature=(MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Set<String> pression = user.getPression();
        Auth auth = method.getDeclaredAnnotation(Auth.class);
        String value = auth.value();
        if(!pression.contains(value)){
         throw new NoAuthException("您没有访问权限");
        }
        o=point.proceed();
        return o;
    }
}
